"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.isEnvFeatureSupported = exports.getDebugInfoFromEnvResult = exports.persistedStateToEnvConfig = exports.configToState = exports.configArrayToStateMap = exports.persistedStateToShippedProposalsState = exports.persistedStateToEnvState = exports.persistedStateToBabelState = exports.replState = exports.envConfigToTargetsString = void 0;

var _PluginConfig = require("./PluginConfig");

var _StorageService = _interopRequireDefault(require("./StorageService"));

var _UriUtils = _interopRequireDefault(require("./UriUtils"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const envConfigToTargetsString = envConfig => {
  const components = [];

  if (envConfig.isElectronEnabled && envConfig.electron) {
    components.push(`Electron-${envConfig.electron}`);
  }

  if (envConfig.isNodeEnabled && envConfig.node) {
    components.push(`Node-${envConfig.node}`);
  }

  return encodeURIComponent(components.join(","));
}; //  Repl state stored in Local storage


exports.envConfigToTargetsString = envConfigToTargetsString;

const loadPersistedState = () => {
  const storageState = _StorageService.default.get("replState");

  return { ..._PluginConfig.replDefaults,
    ...storageState
  };
}; //  Repl state in query string


const urlState = () => {
  const queryState = _UriUtils.default.parseQuery();

  return { ..._PluginConfig.replDefaults,
    ...queryState
  };
};

const replState = () => {
  const hasQueryString = window.location.hash;
  return hasQueryString ? urlState() : loadPersistedState();
};

exports.replState = replState;

const persistedStateToBabelState = (persistedState, config) => ({
  availablePresets: [],
  build: persistedState.build,
  circleciRepo: persistedState.circleciRepo,
  didError: false,
  isLoaded: false,
  isLoading: true,
  version: persistedState.version,
  config
});

exports.persistedStateToBabelState = persistedStateToBabelState;

const persistedStateToEnvState = (persistedState, config, isEnabled) => {
  return { ...persistedStateToBabelState(persistedState, config),
    isLoading: isEnabled,
    isEnabled,
    version: persistedState.envVersion
  };
};

exports.persistedStateToEnvState = persistedStateToEnvState;

const persistedStateToShippedProposalsState = (persistedState, config, isEnabled) => ({
  config,
  isLoading: false,
  isLoaded: false,
  didError: false,
  isEnabled
});

exports.persistedStateToShippedProposalsState = persistedStateToShippedProposalsState;

const configArrayToStateMap = (pluginConfigs, defaults = {}) => pluginConfigs.reduce((reduced, config) => {
  reduced[config.package || config.label] = configToState(config, defaults[config.package || config.label] === true);
  return reduced;
}, {});

exports.configArrayToStateMap = configArrayToStateMap;

const configToState = (config, isEnabled = false) => ({
  config,
  didError: false,
  isEnabled,
  isLoaded: config.isPreLoaded === true,
  isLoading: false,
  plugin: null
});

exports.configToState = configToState;

const persistedStateToEnvConfig = persistedState => {
  const isEnvPresetEnabled = !!persistedState.presets && persistedState.presets.split(",").indexOf("env") >= 0;
  const envConfig = {
    browsers: persistedState.browsers,
    electron: _PluginConfig.envPresetDefaults.electron.default,
    isEnvPresetEnabled,
    isElectronEnabled: false,
    isNodeEnabled: false,
    forceAllTransforms: !!persistedState.forceAllTransforms,
    shippedProposals: !!persistedState.shippedProposals,
    isBuiltInsEnabled: !!persistedState.builtIns,
    isSpecEnabled: !!persistedState.spec,
    isLooseEnabled: !!persistedState.loose,
    node: _PluginConfig.envPresetDefaults.node.default,
    version: persistedState.envVersion,
    builtIns: _PluginConfig.envPresetDefaults.builtIns.default
  };
  decodeURIComponent(persistedState.targets).split(",").forEach(component => {
    try {
      const pieces = component.split("-");
      const name = pieces[0].toLowerCase();
      const value = pieces[1];

      if (name) {
        switch (name) {
          case "electron":
            envConfig.electron = value;
            envConfig.isElectronEnabled = true;
            break;

          case "node":
            envConfig.node = value;
            envConfig.isNodeEnabled = true;
            break;

          default:
            console.warn(`Unknown env target "${name}" specified`);
            break;
        }
      }
    } catch (error) {
      console.error("Error parsing env preset configuration", error);
    }
  });
  return envConfig;
};

exports.persistedStateToEnvConfig = persistedStateToEnvConfig;

const getDebugInfoFromEnvResult = result => {
  const debugInfo = [];

  if (result.modulePlugin) {
    debugInfo.push(`Using modules transform:\n  ${result.modulePlugin}`);
  }

  const targetNames = Object.keys(result.targets);

  if (targetNames.length) {
    debugInfo.push("Using targets:\n" + targetNames.map(name => `• ${name}: ${result.targets[name]}`).join("\n"));
  }

  if (result.transformationsWithTargets.length) {
    debugInfo.push("Using plugins:\n" + result.transformationsWithTargets.map(item => `• ${item.name}`).join("\n"));
  } // This property will only be set if we compiled with useBuiltIns=true


  if (result.polyfillsWithTargets && result.polyfillsWithTargets.length) {
    debugInfo.push("Using polyfills:\n" + result.polyfillsWithTargets.map(item => `• ${item.name}`).join("\n"));
  }

  return debugInfo.join("\n\n");
};

exports.getDebugInfoFromEnvResult = getDebugInfoFromEnvResult;

const isEnvFeatureSupported = (version, feature) => {
  if (!version) return false;
  const parsedVersion = parseInt(version);
  const [min, max] = _PluginConfig.envPresetFeaturesSupport[feature];
  return parsedVersion >= min && parsedVersion <= max;
};

exports.isEnvFeatureSupported = isEnvFeatureSupported;